package com.cn.lyl.service;

import com.cn.lyl.dao.LawyerDao;
import com.cn.lyl.model.LawyerModel;
import com.cn.lyl.util.IO;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LawyersService {

    private String split ="@@@@@@";

    public List<LawyerModel> getLawyersList(String path){
        LawyerDao dao = new LawyerDao();
        File file=IO.createNote(path,"lawyers.txt");
        writeNote(file);
        String result = IO.readNote(file);
        List<LawyerModel> lawyers=setLawyerListData(result);
        return lawyers;
    }

    private List<LawyerModel> setLawyerListData(String result) {
        List<LawyerModel> lawyers = new ArrayList<LawyerModel>();
        String[] results = result.split(split);
        String name = results[0];
        String[] names = name.split(",");
        String intro = results[1];
        String[] intros = intro.split(",");
        String role = results[2];
        String[] roles = role.split(",");
        String head = results[3];
        String[] heads = head.split(",");
        for(int i=0;i < names.length;i++){
            LawyerModel lawyer = new LawyerModel(names[i],intros[i],roles[i],heads[i]);
            lawyers.add(lawyer);
        }
        return lawyers;
    }

    private void writeNote(File file){

        try {
            OutputStream outputStream = new FileOutputStream(file);
            LawyerDao lawyerDao = new LawyerDao();
            String namesToString = Arrays.toString(lawyerDao.getNames());
            String introsToString =Arrays.toString(lawyerDao.getIntros());
            String rolesToString = Arrays.toString(lawyerDao.getRoles());
            String headsToString = Arrays.toString(lawyerDao.getHeads());
            namesToString=namesToString.replace("[","").replace("]","").replace(" ","");
            introsToString=introsToString.replace("[","").replace("]","").replace(" ","");
            rolesToString=rolesToString.replace("[","").replace("]","").replace(" ","");
            headsToString=headsToString.replace("[","").replace("]","").replace(" ","");
            outputStream.write(namesToString.getBytes());
            outputStream.write(split.getBytes());
            outputStream.write(introsToString.getBytes());
            outputStream.write(split.getBytes());
            outputStream.write(rolesToString.getBytes());
            outputStream.write(split.getBytes());
            outputStream.write(headsToString.getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        LawyersService lawyersService = new LawyersService();
        List<LawyerModel> lawyers=lawyersService.getLawyersList("D:\\新建文件夹\\folder\\jsp\\02\\out");
        for(LawyerModel lawyer:lawyers){
            System.out.println(lawyer.getIntro());
        }
    }


}
